package com.bw.interceptor;

import com.alibaba.fastjson.JSON;
import com.bw.common.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取浏览器发送过来的所有cookie
        Cookie[] cookies = request.getCookies();

        boolean b = false; //  默认拦截所有人

        if (cookies != null) {
            for (Cookie cookie : cookies) {  // 从cookie中过滤出  token令牌
                String name = cookie.getName();
                if (name.equals("token")) {
                    String token = cookie.getValue();
                    // 验证令牌是否有效
                    b = JwtUtils.validToken(token);
                }
            }
        }

        if (b == false) {
            response.sendRedirect("/loginPage.do");
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
